package com.jsh.erp.service.scorder;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.datasource.vo.ScOrderVOlist;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.BaseResponseInfo;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class ScOrderService {
    private Logger logger = LoggerFactory.getLogger(ScOrderService.class);

    @Resource
    private ScOrderMapper scOrderMapper;
    @Resource
    private ScOrderMapperEx scOrderMapperEx;
    @Resource
    private LogService logService;
    @Resource
    private AccountHeadMapperEx accountHeadMapperEx;
    @Resource
    private DepotHeadMapperEx depotHeadMapperEx;
    @Resource
    private SupplierService supplierService;

    public ScOrder getScOrder(long id)throws Exception {
        ScOrder result=null;
        try{
            result=scOrderMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<ScOrder> getOrderListByIds(String ids)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        List<ScOrder> list = new ArrayList<>();
        try{
            ScOrderExample example = new ScOrderExample();
            example.createCriteria().andIdIn(idList);
            list = scOrderMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }
    public List<ScOrderVOlist> select(String khxx, String guige, String beignTime, String ddNum, String endTime, String status, int offset, int rows)throws Exception {
        List<ScOrderVOlist> list=null;
        try{
            list= scOrderMapperEx.selectByConditionScOrderVO(khxx,guige,beignTime,endTime,ddNum,status,offset, rows);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public Long countOrder(String khxx, String guige,String beignTime,String endTime,String ddNum,String status)throws Exception {
        Long result=null;
        try{
            result= scOrderMapperEx.countsByScOrder(khxx,guige,beignTime,endTime,ddNum,status);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertScOrder(String beanJson, HttpServletRequest request)throws Exception {
        ScOrder scOrder = JSONObject.parseObject(beanJson, ScOrder.class);
        User curUser = (User)request.getSession().getAttribute("user");
        //默认是未生产
        scOrder.setStatus("0");
        int result=0;
        try{
            result = scOrderMapper.insertSelective(scOrder);
            logService.insertLog("经手人",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(curUser.getUsername()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertScOrder(ScOrder scOrder, HttpServletRequest request)throws Exception {
        User curUser = (User)request.getSession().getAttribute("user");
        int result=0;
        try{
            result = scOrderMapper.insertSelective(scOrder);
            logService.insertLog("经手人",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(curUser.getUsername()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
            public int updateScOrder(String beanJson, Long id, HttpServletRequest request)throws Exception {
        ScOrder scOrder = JSONObject.parseObject(beanJson, ScOrder.class);
        ScOrder idScOrder = scOrderMapper.selectByPrimaryKey(id);
        User curUser = (User)request.getSession().getAttribute("user");
        scOrder.setStatus(idScOrder.getStatus());
        scOrder.setGongxu(idScOrder.getGongxu());
        int result=0;
        try{
            result = scOrderMapper.updateByPrimaryKeySelective(scOrder);
            logService.insertLog("经手人",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(curUser.getUsername()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteScOrder(Long id, HttpServletRequest request)throws Exception {
        int result=0;
        try{
            result= scOrderMapper.deleteByPrimaryKey(id);
            logService.insertLog("经手人",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_DELETE).append(id).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteScOrder(String ids, HttpServletRequest request) throws Exception{
        int result=0;
        String[] idsArr = ids.split(",");
        try{
            result= scOrderMapperEx.batchDeleteOrderByIds(idsArr);
            logService.insertLog("经手人", "批量删除,id集:" + ids, request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int countMax() throws Exception{
        int result=0;
        try{
            result= scOrderMapperEx.countMax();
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public BaseResponseInfo importExcel(List<ScOrder> mList) throws Exception {
        logService.insertLog("生产订单",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_IMPORT).append(mList.size()).append(BusinessConstants.LOG_DATA_UNIT).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        BaseResponseInfo info = new BaseResponseInfo();
        Map<String, Object> data = new HashMap<String, Object>();
        try {
            for(ScOrder s: mList) {
                scOrderMapper.insertSelective(s);
            }
            info.code = 200;
            data.put("message", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            info.code = 500;
            data.put("message", e.getMessage());
        }
        info.data = data;
        return info;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteByIds(String ids)throws Exception {
        String [] idArray=ids.split(",");
        int result =0;
        try{
            result=scOrderMapperEx.batchDeleteOrderByIds(idArray);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
}
